package org.bapoint.reactadmin.py;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import java.io.InputStream;
import java.io.OutputStream;

public class RemotePythonExecution {
    public static void main(String[] arg) {
        try {
            JSch jsch = new JSch();

            // 替换为你的云服务器用户名、主机名/IP及密码或密钥
            String user = "root";
            String host = "121.41.62.253";
            String password = "2232292044@qq.com"; // 或使用密钥对进行认证

            Session session = jsch.getSession(user, host, 22);
            session.setPassword(password);

            // 配置免密钥登录（如果使用密钥对）
            // jsch.addIdentity("/path/to/private/key");

            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();

            ChannelExec channelExec = (ChannelExec) session.openChannel("exec");

            // 假设你的Python脚本路径在云服务器上为/home/user/myscript.py
            String command = "python /home/test.py";

            channelExec.setCommand(command);

            // 获取输入流和输出流
            InputStream in = channelExec.getInputStream();
            OutputStream out = channelExec.getOutputStream();
            channelExec.connect();

            // 读取并打印脚本的输出
            byte[] buffer = new byte[2048];
            while (true) {
                while (in.available() > 0) {
                    int i = in.read(buffer, 0, 2048);
                    if (i < 0) break;
                    System.out.print(new String(buffer, 0, i));
                }
                if (channelExec.isClosed()) {
                    if (in.available() > 0) continue;
                    System.out.println("exit-status: " + channelExec.getExitStatus());
                    break;
                }
                Thread.sleep(1000);
            }

            channelExec.disconnect();
            session.disconnect();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}